<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/13
 * Time: 17:32
 */

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\WechatMenu;
use Validator;

class MenuController extends Controller
{
    public $wechatMenuModel;
    public $rootMenu;

    public function __construct(Request $request, WechatMenu $wechatMenu)
    {
        parent::__construct();
        $this->request = $request;
        $this->wechatMenuModel = $wechatMenu;
        $this->rootMenu = $this->wechatMenuModel->find(1);
    }

    public function index(){
        $where = [];
        //$this->wechatMenuModel->rebuild(true);
        $this->data["menus"]  = $this->rootMenu->children()->get();
        return $this->showView("menu_index");
    }

    public function edit(){
        $firstChilds = $this->rootMenu->children()->get();
        $this->data["firstChilds"][$this->rootMenu->id] = $this->rootMenu->name;
        foreach ($firstChilds as $child) {
            $this->data["firstChilds"][$child->id] = $child->name;
        }
        // = $this->wechatMenuModel->where("depth","0")->get();
        $this->data["menuTypeList"] = $this->wechatMenuModel->menuTypeList;
        $this->data["wechatMenu"] = $this->wechatMenuModel->firstOrNew(["id"=>$this->request->id]);

        return $this->showView("menu_edit");
    }

    public function save(){
        $rules = [
            "parent_id" => "required",
            "name" => "required",
            "value" => "required",
            "typecode" => "required",
            //"orderby" => "required",
        ];
        $validator = Validator::make($this->request->all(),$rules);
        if($validator->fails()){
            return back()->withErrors($validator->errors());
        }
        $param = $this->request->only("parent_id", "name", "value" ,"typecode");
        $parentNode = $this->wechatMenuModel->find($param['parent_id']);

        if($this->request->id){
            $this->wechatMenuModel->find($this->request->id)->update($param);
        }else {
            if (($parentNode->id ==1 && $parentNode->children()->count()>=3) || ($parentNode->id != 1&&$parentNode->children()->count()>=5)){
                return redirect("menu")->with("alert",["message"=>"主菜单不能多于3个，子菜单不能多于5个","style"=>"danger"]);
            }
            $parentNode->children()->create($param);
        }
        return redirect("menu")->with("alert",["message"=>"保存成功","style"=>"success"]);;
    }

    public function delete(){
        $this->wechatMenuModel->find($this->request->id)->delete();
        return redirect("menu")->with("alert",["message"=>"删除成功","style"=>"success"]);;
    }

    public function order(){
        $id = $this->request->id;
        $act = $this->request->act;
        try {
            $node = $this->wechatMenuModel->find($id);
            if ($act == "left") {
                $node->moveLeft();
            } elseif ($act == "right") {
                $node->moveRight();
            }
        }catch (\Exception $e){

        }

        return redirect("menu")->with("alert",["message"=>"更改顺序成功","style"=>"success"]);;

    }

    public function sync(){
        $firstList = $this->rootMenu->children()->get();
        $buttons = [];

        foreach ($firstList as $key=>$item){
            $buttons[$key] = [
                "type"=>$item->typecode,
                "name"=>$item->name,
                $this->getdataname($item->typecode) => $item->value,
            ];

            if($item->children()->count()>0) {
                unset($buttons[$key]["type"], $buttons[$key][$this->getdataname($item->typecode)]);
                foreach ($item->children()->get() as $k => $child) {
                    $buttons[$key]["sub_button"][] = [
                        "type" => $child->typecode,
                        "name" => $child->name,
                        $this->getdataname($child->typecode) => $child->value,
                    ];
                }

            }
        }
        $result = \EasyWeChat::menu()->add($buttons);
        return redirect("menu")->with("alert",["message"=>"菜单同步成功","style"=>"success"]);;
        //return \Response::json($result);
    }

    public function getfromremote(){
        $memus = \EasyWeChat::menu()->all();
        $menus2 = $memus["menu"]['button'];
        $newArr = json_decode(preg_replace(["/\"sub_button\"/","/\"type\"/","/media_id|url|key/"],["\"children\"","\"typecode\"","value"],json_encode($menus2)),true);

        $this->rootMenu->makeTree($newArr);

        return redirect("menu")->with("alert",["message"=>"下载菜单完成","style"=>"success"]);;
    }

    private function getdataname($typecode){
        switch ($typecode) {
            case "media_id":
            case "view_limited":
                return "media_id";
            case "view":
                return "url";
            default :
                return "key";
        }
    }

}